package com.shqcjd.preinstallglass.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.app.AppConstant;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.eventbus.FinishVideotape;
import com.shqcjd.preinstallglass.model.eventbus.VideoReleaseEvent;
import com.shqcjd.preinstallglass.model.pojo.EquipmentAbnormalBean;
import com.shqcjd.preinstallglass.ui.activity.remote.ExpertTypeActivity;
import com.shqcjd.preinstallglass.ui.adapter.EquipmentAbnormalAdapter;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class EquipmentAbnormalActivity extends BaseActivity {
    @BindView(R.id.rv_equipment_abnormal)
    public RecyclerView rvEquipmentAbnormal;
    @BindView(R.id.btn_finish)
    public Button btnFinish;
    @BindView(R.id.btn_guide)
    Button btnGuide;


    private Context context;
    private EquipmentAbnormalAdapter equipmentAbnormalAdapter;
    public List<RadioGroup> radioGroupList = new ArrayList<>();

    public List<LinearLayout> linearList = new ArrayList<>();

    private int eId, tId;
    private final int END_CODE = 12312;
    private Integer prid = 0;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_equipment_abnormal;
    }

    @Override
    public void init() {
        super.init();
        eId = getIntent().getIntExtra("eId", -1);
        tId = getIntent().getIntExtra("tId", -1);
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        EventBus.getDefault().register(this);//订阅
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnGuide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, ExpertTypeActivity.class));
            }
        });
        getData();
    }

    private void getData() {
        ApiService.equipmentAbnormalHttp(tId, eId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<EquipmentAbnormalBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<EquipmentAbnormalBean> responseData) {
                        if(responseData.retCode!=10000){
                            return;
                        }
                        rvEquipmentAbnormal.setLayoutManager(new LinearLayoutManager(context));
                        List<EquipmentAbnormalBean.EquipmentPartBean> mList = new ArrayList<>();
                        mList.addAll(responseData.data.equipment_part);
                        equipmentAbnormalAdapter = new EquipmentAbnormalAdapter(mList, EquipmentAbnormalActivity.this, responseData.data.equipment_id);
                        rvEquipmentAbnormal.setAdapter(equipmentAbnormalAdapter);
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    public void srollRv( int y, int h){
        rvEquipmentAbnormal.smoothScrollBy(rvEquipmentAbnormal.getScrollX(), rvEquipmentAbnormal.getScrollY()+y+h);
    }

    private int mepId, meId;
    private String value;
    public void putCheckResultHttp(int epId, String v, int status, int eId) {
        value = v;
        mepId = epId;
        meId = eId;
        Map<String, String> map = new HashMap<>();
        map.put("task_id", tId+"");
        map.put("equipment_part_item_id", eId+"");
        map.put("value", v);
        map.put("status", status+"");
        map.put("equipment_id", epId+"");

        ApiService.putCheckResultHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> responseData) {
                        if (responseData.retCode == 10000) {
                            if (status == -1) {
                                prid = responseData.data;
                                //发送eventbus 关闭全程录像camera资源后打开组设备异常页面
                                EventBus.getDefault().post(new FinishVideotape(AppConstant.ABNORMAL_GROUP_CODE));
                            }else{
                                if(isCheckAll()){
                                    finish();
                                }
                            }
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private boolean isCheckAll() {
        for (int i = 0; i < radioGroupList.size(); i++) {
            RadioGroup radioGroup = radioGroupList.get(i);
            RadioButton rb1 = (RadioButton) radioGroup.getChildAt(1);
            RadioButton rb2 = (RadioButton) radioGroup.getChildAt(3);
            if (!rb1.isChecked() && !rb2.isChecked()) {
                return false;
            }
        }
        return true;
    }

    public int oldFocusPos = -1;
    public void focusItem(int i){
        if(oldFocusPos!=-1){
            ColorDrawable colorDrawable = new ColorDrawable(
                    getResources().getColor(R.color.equipment_abnormal_title_bg));
            linearList.get(oldFocusPos).setBackground(colorDrawable);
        }
        ColorDrawable colorDrawable = new ColorDrawable(
                getResources().getColor(R.color.equipment_inspect_btn_bg));
        linearList.get(i+1==linearList.size()?i:i+1).setBackground(colorDrawable);
        oldFocusPos = i+1==linearList.size()?i:i+1;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==END_CODE){
            if(isCheckAll()){
                finish();
            }
        }
    }

    /**
     * 已释放全程录像资源
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoReleaseEvent(VideoReleaseEvent event) {
        if (event.request_code==AppConstant.ABNORMAL_GROUP_CODE&&prid!=0) {
            Intent it = new Intent(context, AbnormalActivity.class);
            it.putExtra("prid", prid);
            it.putExtra("tId",tId);
            it.putExtra("epId",mepId);
            it.putExtra("eId",meId);
            it.putExtra("value",value);
            startActivityForResult(it, END_CODE);
        }

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//解除订阅
    }
}
